<?php
/**
 * Created by PhpStorm.
 * User: 悟能科技
 * Date: 2018/10/12
 * Time: 9:25
 */

namespace app\mobile\controller;


use app\common\controller\Ydhwork;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\YdhOpen;
use app\common\model\YdhUser;
use app\common\model\YdhUserCate;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Ordergoods extends Mobilebase
{

    //用户信息
    public function index(Request $request){
        $arr = $request->param();

        $this->_init();
        $info = $this->get_ydhuser($arr['card_id']);

        if ($info) {
            $YdhOpen = new YdhOpen();

            $YdhUser = new YdhUser();
            $map['a.openid'] = $info['openid'];
            $user = $YdhUser->alias('a')->join('wn_ydh_user_cate b', 'a.customertypeId=b.cate_id', 'left')
                ->where($map)
                ->field('a.top_mid,a.code,a.name,a.contactor,a.mobile,a.username,a.customertypeId as user_cate,b.name as level,a.mobile as phone,a.card_id')->find();
//            halt($user);
            $open = $YdhOpen->where('top_mid',$info['top_mid'])->field('price_cate_id')->find();
            $this->assign('open',$open);
            $this->assign('user', $user);
            return $this->fetch();
        }else{
            $this->redirect('ordergoods/register',['card_id'=>$arr['card_id']]);
        }
    }

    //用户注册
    public function register(Request $request){
        $arr = $request->param();
        $this->_init();
        $info = $this->getuserinfo($arr,1);
        $ydhinfo = $this->get_ydhuser($arr['card_id']);
        $YdhOpen = new YdhOpen();
        if (!$ydhinfo) {
            if ($request->isAjax()) {
                $param = $request->post();
                $data['top_mid'] = $info['top_mid'];
                //END
                $data['code'] = $info['code'];
                $data['name'] = $info['name'];
                $data['contactor'] = $info['name'];
                $data['mobile'] = $info['phone'];
                $data['userName'] = $param['username'];
                $data['password'] = $param['password'];
                $data['customertypeId'] = $YdhOpen->where('top_mid',$info['top_mid'])->value('default_cate_id');
                $data['activeCustomer'] = 1;
                $OrderObj = new Ydhwork();
                $ares = $OrderObj->create_user($data);
//                return json($ares);
                if ($ares['code'] == 200) {
                    $data['user_id'] = $ares['data']['id'];
                    $data['mid'] = $info['mid'];
                    $data['openid'] = $info['openid'];
                    $data['c_id'] = $info['c_id'];
                    $data['us_id'] = $info['id'];
                    $data['card_id'] = $info['card_id'];
                    $data['create_time'] = time();
                    $data['username'] = $param['username'];
                    $YdhUser = new YdhUser();
                    $YdhUser->allowField(true)->save($data);

                    $ares['code'] = '0';
                    $ares['url'] = url('mobile/ordergoods/pay', 'card_id=' . $arr['card_id']);
                    $ares['message'] = '注册成功';

                }
                return json($ares);
            } else {
                $this->assign('user', $info);
                return $this->fetch();
            }
        }else{
            $this->redirect('ordergoods/index',['card_id'=>$arr['card_id']]);
        }
    }

    //用户付费
    public function pay(Request $request){
        $arr = $request->param();
        $this->_init();
        $info = $this->getuserinfo($arr,1);
        if ($request->isAjax()){
            $param = $request->post();
            if ($param['price'] > 0) {
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $config = $Merchant->where(array('id' => $param['mid']))->field('sub_mch_id,agent,wx_open_id')->find();
                $agent = $Agent->where(array('id' => $config['agent']))->field('partnerid,partnerkey,wx_open_id')->find();
                $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->field('authorizer_appid')->find();
                $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
                $options = array(
                    'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                    'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                    'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                );
//                return json($options);
                $weObj = new Wxobjopen($options);
                $price = $param['price'];
                $appid = $users['authorizer_appid'];
                $mch_id = $agent['partnerid'];
                $out_trade_no = $param['orderid'];
                $body = "客户升级";
                $sub_mch_id = $config['sub_mch_id'];
                $sub_appid = $userwx['authorizer_appid'];
                $total_fee = $price * 100;
                $data['orderid'] = $out_trade_no;
                $data['mid'] = $param['mid'];
                $data['openid'] = $param['openid'];
                $data['pay_statu'] = 0;
                $data['pay_cate'] = 'pay';
                $data['price'] = $price;
                $data['yf_price'] = $price;
                $data['zk_price'] = $data['yf_price'] - $data['price'];
                $data['add_time'] = time();
                $data['attach'] = 'ydh_upgrade';
                $Paylog = new Paylog();
                $Paylog->allowField(true)->save($data);
                $sub_openid = $param['openid'];
                $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
                $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
                $nonce_str = $weObj->generateNonceStr();
                $partnerkey = $options['partnerkey'];
                $arrdata = array(
                    "appid" => $appid,
                    'sub_appid' => $sub_appid,
                    "mch_id" => $mch_id,
                    "sub_mch_id" => $sub_mch_id,
                    "nonce_str" => $nonce_str,
                    "body" => $body,
                    "out_trade_no" => $out_trade_no,
                    "total_fee" => $total_fee,
                    "spbill_create_ip" => $spbill_create_ip,
                    "notify_url" => $notify_url,
                    "sub_openid" => $sub_openid,
                    'trade_type' => 'JSAPI'
                );
                $pay_xml = $weObj->createWxPackageXmls($arrdata,$partnerkey);
                $pay_xml = $weObj->get_pay_id($pay_xml);
//                return json($pay_xml);
                if ($pay_xml['return_code'] == 'SUCCESS') {
                    $prepay_id = $pay_xml['prepay_id'];
                    $jsApiObj["appId"] = $appid;
                    $timeStamp = time();
                    $jsApiObj["timeStamp"] = "$timeStamp";
                    $jsApiObj["nonceStr"] = $nonce_str;
                    $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                    $jsApiObj["signType"] = "MD5";
                    $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                    //状态码
                    $jsApiObj['code'] = 0;
                } else {
                    $jsApiObj = ['code' => 9002, 'message' => '支付失败！'];
                }
            } else {
                $jsApiObj = ['code' => 9001, 'message' => '请输入正确的充值金额！'];
            }

            return json($jsApiObj);
        }else {
            $YdhOpen = new YdhOpen();
            $cate_id = $YdhOpen->where('top_mid',$info['top_mid'])->value('default_cate_id');
            $ydhinfo = $this->get_ydhuser($arr['card_id']);
            if ($ydhinfo['customertypeId'] == $cate_id) {
                $ydhinfo = $YdhOpen->where(['top_mid' => $info['top_mid']])->find();
                $this->assign('info', $ydhinfo);
                $this->assign('user', $info);
                return $this->fetch();
            }else{
                $this->redirect('ordergoods/index',['card_id'=>$arr['card_id']]);
            }
        }
    }

    /*
    * 支付结束
    *
    */
    public function r_payover()
    {
        if (request()->isAjax()) {
            $request = request();
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $request->post('id');
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $request->post('orderid');
            $nonce_str = $weObj->generateNonceStr();
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
            $payorder_xml = $weObj->getPayNum($pay_xml);
            $orderno = $payorder_xml['transaction_id'];
            $pay_zt = $payorder_xml['trade_state'];
            if ($pay_zt == "SUCCESS") {
                $array = array('code' => 0, 'message' => "支付成功",'url'=>url('mobile/ordergoods/orderinfo','orderid='.$out_trade_no));

            } else {
                $array = array('code' => 1, 'message' => "支付失败",'url'=>'');
            }
            return json($array);
        }
    }

    //订单信息
    public function orderinfo(Request $request){
        $Paylog = new Paylog();
        $YdhUser = new YdhUser();
        $param = $request->param();
        $info = $Paylog->where(['orderid'=>$param['orderid']])->find();
        $map['openid'] = $info['openid'];
        $info['card_id'] = $YdhUser->where($map)->value('card_id');
        $this->assign('info',$info);
        return $this->fetch();
    }


    //获取订单
    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }



    //客户信息
    public function get_ydhuser($card_id){
        $appid = $this->getappid($card_id);
        $openid = Session::get($appid.'_openid');
        $YdhUser = new YdhUser();
        $info = $YdhUser->where('openid',$openid)->find();
        return $info;
    }

    public function user_cate_list(Request $request){
        if ($request->isAjax()){
            $param = $request->post();
            //OBJ
            $OrderObj = new Orderapi();
            $res = $OrderObj->create_user();


        }
    }


}